<template>
  <div class="page-container">
    <div class="control-container">
      <div class="left-panel shrink-panel" :class="isWide?'':'narrow'">
        <div class="shrink-btn-panel">
          <i :class="isWide?'el-icon-arrow-left':'el-icon-arrow-right'" @click="isWide = !isWide" />
        </div>
        <OutletTree
          v-if="isWide"
          @handleNodeClick="handleNodeClick"
        />
      </div>
      <div class="right-panel overflow-x">
        <div class="search-panel">
          <el-form :inline="true" label-width="100">
            <el-form-item label="最近:">
              <el-radio-group v-model="radioData" class="search-radio-group" @change="changeRadio()">
                <el-radio :label="1">当天</el-radio>
                <el-radio :label="2">3天</el-radio>
                <el-radio :label="3">7天</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="query.startDate"
                type="datetime"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :clearable="false"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="query.endDate"
                type="datetime"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :clearable="false"
              />
            </el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button v-show="showData" v-loading="exportLoading" type="primary" @click="handleExport">导出</el-button>
            <el-button v-show="showData" type="primary" @click="handleChange(true)">切换曲线</el-button>
            <el-button v-show="lineChartShow" type="primary" @click="handleChange(false)">切换表格</el-button>
            <el-button type="primary" @click="handleWarranty">查看质保</el-button>
          </el-form>
        </div>
        <div>
          <div v-if="query.outletId === null && tableData.length === 0" class="choose-outlet-panel">请导航树选择对应节点</div>
          <el-table
            v-if="showData"
            ref="multipleTable"
            v-loading="tableLoading"
            class="grid-data-table"
            height="calc(100vh - 320px)"
            :data="tableData"
          >
            <el-table-column fixed="left" align="center" type="index" width="80" />
            <el-table-column fixed="left" prop="realTimeStr" label="时间" width="140" />
            <template v-for="(item,index) in tableHead">
              <el-table-column :key="index" :prop="item.prop" :label="item.label" min-width="120" :class="changeColorByDataStatus(item.dataStatus)">
                <template slot="header" slot-scope="scope">
                  <span style="display:inline-block; text-align: center" v-html="wrapLabel(scope.column.label)" />
                </template>
                <template slot-scope="scope">
                  <span style="margin-left: 10px" :class="changeColorByDataStatus(scope.row[item.prop+'_dataStatus'])">{{ scope.row[item.prop] }}</span>
                </template>
              </el-table-column>
            </template>
          </el-table>
          <div class="pagination-container">
            <Pagination
              v-if="showData"
              v-show="query.total>0"
              :total="query.total"
              :page.sync="query.page"
              :limit.sync="query.limit"
              @pagination="handleQueryTable"
            />
          </div>
          <div v-if="lineChartShow" style="height: calc(100vh - 320px);">
            <LineChart
              ref="chars"
              v-loading="lineLoading"
              :chart-data="chartData"
              time-type="{i}:{s}"
            />
          </div>
        </div>
      </div>
    </div>
    <SelectOutletEquipment
      :dialog-visible="dialogVisible"
      :tree-id="query2.treeId"
      :tree-type="query2.treeType"
      @closeDialog="closeDialog"
      @flushPage="handleSelect"
    />
  </div>
</template>

<script>
import OutletTree from '@/components/Tree/outletTree'
import Pagination from '@/components/Pagination'
import { downloadFileHasFile } from '@/utils'
import { selectRealtimeData, exportRealtimeData, selectRealtimeBrokenData } from '@/api/dataQuery/dataQuery'
import { getDatefmt, getColorByDataStatus } from '@/utils/common'
import LineChart from './components/LineChart'
import SelectOutletEquipment from './components/SelectOutletEquipment'
import { getPage } from '@/api/base/outletEquipment'
export default {
  name: 'RealtimeData',
  components: {
    Pagination, OutletTree, LineChart, SelectOutletEquipment
  },
  data() {
    return {
      isWide: true,
      query: {
        startDate: null, endDate: null, outletId: null,
        total: 0,
        page: 1,
        limit: 20
      },
      query2: {
        treeType: null, treeId: null
      },
      tableLoading: false,
      // 存储是列的属性:列的值
      tableData: [],
      tableHead: [],
      radioData: 1,
      showData: false,
      dialogVisible: false,
      lineChartShow: false,
      lineLoading: false,
      exportLoading: false,
      chartData: {}
    }
  },
  created() {
    this.changeRadio()
  },
  methods: {
    wrapLabel(val) {
      let res = val
      if (res) {
        const index = res.indexOf('（')
        if (index !== -1) {
          res = val.substring(0, index) + '<br/>'
          res += val.substring(index, val.length)
        }
      }
      return res
    },
    changeColorByDataStatus(status) {
      return getColorByDataStatus(status)
    },
    // 切换曲线
    handleChange(val) {
      this.lineChartShow = val
      this.handleQuery()
    },
    // 查询
    handleQuery() {
      if (this.lineChartShow) {
        this.hadnleQueryLine()
      } else {
        this.handleQueryTable()
      }
    },
    // 查看合同
    handleWarranty() {
      this.dialogVisible = true
    },
    // 点击树
    handleNodeClick(data) {
      this.query = {
        ...this.query,
        outletId: null,
        total: 0,
        page: 1,
        limit: 20
      }
      this.query2.treeType = data.level
      this.query2.treeId = data.id
      if (data.level === 3) {
        this.showData = true
        this.query.outletId = data.id
        this.handleQuery()
      } else {
        this.$message.warning('请选择排口')
      }
    },
    // 查询折线
    hadnleQueryLine() {
      const query = JSON.parse(JSON.stringify(this.query))
      this.lineLoading = true
      this.lineChartShow = true
      this.showData = false
      selectRealtimeBrokenData(query).then(res => {
        if (res.data.data === null || res.data.data.length === 0) {
          this.$message.warning('该排口暂无数据')
        } else {
          this.chartData = res.data.data
        }
        this.lineLoading = false
      })
    },
    // 查询合同
    handleSelect() {
      this.tableLoading = true
      const query = JSON.parse(JSON.stringify(this.query))
      getPage(query).then(res => {
        this.tableData = res.data.data.records
        this.query.total = res.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 查询表格
    handleQueryTable() {
      this.tableLoading = true
      this.lineChartShow = false
      this.showData = true
      this.tableData = []
      this.tableHead = []
      const query1 = JSON.parse(JSON.stringify(this.query))
      selectRealtimeData(query1).then(res => {
        this.tableHead = res.data.column
        var recordsTemp = res.data.page.records
        if (recordsTemp != null) {
          for (let i = 0; i < recordsTemp.length; i++) {
            var temp = recordsTemp[i]
            // 计算因子 id
            var factorDtoList = temp.factorDtoList
            if (factorDtoList != null) {
              for (let j = 0; j < factorDtoList.length; j++) {
                temp[factorDtoList[j].factorLibraryIdStr] = this.returnFloat(factorDtoList[j].val)
                temp[factorDtoList[j].factorLibraryIdStr + '_z'] = this.returnFloat(factorDtoList[j].zsVal)
                if (factorDtoList[j].zsVal) {
                  temp[factorDtoList[j].factorLibraryIdStr + '_z_dataStatus'] = factorDtoList[j].dataStatus
                } else {
                  temp[factorDtoList[j].factorLibraryIdStr + '_dataStatus'] = factorDtoList[j].dataStatus
                }
              }
            }
          }
        }
        this.tableData = recordsTemp
        this.query.total = res.data.page.total
        this.$nextTick(() => {
          this.$refs.multipleTable.doLayout()
          // el-table加ref="multipleTable"
        })
        this.tableLoading = false
      }).catch(reason => {
        this.tableLoading = false
      })
    },
    returnFloat(value) { // 格式化数据 统一小数点后三位，不足的补
      if (value > 9999) {
         	return Math.round(value)
      }
      var value = Math.round(parseFloat(value) * 1000) / 1000
      var xsd = value.toString().split('.')
      if (xsd.length === 1) {
        value = value.toString() + '.000'
        return value
      }
      if (xsd.length > 1) {
        if (xsd[1].length === 1) {
          value = value.toString() + '00'
          return value
        } else {
          if (xsd[1].length === 2) {
            value = value.toString() + '0'
          }
          return value
        }
      }
    },
    handleExport() {
      const query1 = JSON.parse(JSON.stringify(this.query))
      this.exportLoading = true
      exportRealtimeData(query1).then(result => {
        downloadFileHasFile(result)
        this.exportLoading = false
      }).catch(() => {
        console.log('此处错误')
        this.exportLoading = false
      })
    },
    changeRadio() {
      const date = new Date()
      this.query.endDate = getDatefmt(date, 'yyyy-MM-dd hh:mm:ss')
      if (this.radioData === 1) {
        this.query.startDate = getDatefmt(new Date(), 'yyyy-MM-dd') + ' 00:00:00'
      } else if (this.radioData === 2) {
        this.query.startDate = getDatefmt(new Date(new Date().setDate(date.getDate() - 3)), 'yyyy-MM-dd hh:mm:ss')
      } else {
        this.query.startDate = getDatefmt(new Date(new Date().setDate(date.getDate() - 7)), 'yyyy-MM-dd hh:mm:ss')
      }
    },
    closeDialog() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
